#include <head.h>


void copy_file(int src_fd,int desk_fd,off_t start,off_t end)
{
    char buf[1024];
    lseek(src_fd,start,SEEK_SET);
    lseek(desk_fd,start,SEEK_SET);

    size_t byte_read = 0;
    size_t byte_write = 0;

    while(start < end){
        if ((byte_read = read(src_fd,buf,sizeof(buf))) <= 0)
        {
            break;
        }
        if ((byte_write = write(desk_fd,buf,byte_read))<=0)
        {
            break;
        }
        
        start += byte_write;
    }
}

int main(int argc,char *argv[])
{
    if (argc != 3)
    {
        printf("Usage: %s src_file desk_file start end\n",argv[0]);
        exit(1);
    }
    int desk_fd = open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
    if (desk_fd<0)
    {
        ERRLOG("open");
    }
    int src_fd = open(argv[2],O_RDONLY,0666);
    if (src_fd<0)
    {
        ERRLOG("open");
    }
    struct stat file_stat;
    if (fstat(src_fd,&file_stat)<0)
    {
        ERRLOG("fstat");
        close(desk_fd);
        close(src_fd);
        exit(1);
    }

    off_t file_size = file_stat.st_size;
    off_t part_size = file_size / 2;

    pid_t pid = fork();
    if (pid<0)
    {
        ERRLOG("fork");
        close(desk_fd);
        close(src_fd);
        exit(1);
    }
    if (pid == 0)
    {
        off_t start = 0;
        off_t end = part_size;
        copy_file(src_fd,desk_fd,start,end);
        close(desk_fd);
        close(src_fd);
        exit(0);
        
    }else{
        off_t start = part_size;
        off_t end = file_size;
        copy_file(src_fd,desk_fd,start,end);
        close(desk_fd);
        close(src_fd);
        wait(NULL);
        
    }
    
    return 0;
 
}